package com.avic.rong.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginActivity;
import com.avic.rong.api.login_register.WxLoginApi;
import com.avic.rong.api.mine.AccountSecurityApi;
import com.avic.rong.api.mine.AccountWxBindApi;
import com.avic.rong.api.mine.UnBindWxApi;
import com.avic.rong.bean.login_register.WeChatBean;
import com.avic.rong.bean.mine.AccountSecurityBean;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.google.gson.Gson;
import com.luck.picture.lib.dialog.CustomDialog;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

//账号安全
public class AccountSecurityActivity extends BaseActivity {

    @BindView(R.id.tv_up_phone)
    TextView tv_up_phone;
    @BindView(R.id.tv_bind_wx)
    TextView tv_bind_wx;
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;
    private Unbinder bind;

    @BindView(R.id.rl_up_phone)
    RelativeLayout rl_up_phone;
    @BindView(R.id.rl_up_pwd)
    RelativeLayout rl_up_pwd;
    @BindView(R.id.rl_bind_wx)
    RelativeLayout rl_bind_wx;
    private String mobile;
    private UMShareAPI mShareAPI;
    private String login_token;
    private AccountSecurityApi accountSecurityApi;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_account_security;
    }

    @Override
    protected void initView() {
        tvTitle.setText("账号与安全");
        ivRight.setBackgroundResource(R.mipmap.slh);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mShareAPI = UMShareAPI.get(this);

        if (SharedPreferencesUtil.isLogin()) {
            login_token = SharedPreferencesUtil.getLoginToken();
        }
        accountSecurityApi = new AccountSecurityApi(this, accountSecurityListener);
        accountSecurityApi.setToken(login_token);
        accountSecurityApi.setCache(false);
        accountSecurityApi.setCancel(false);
        accountSecurityApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(accountSecurityApi);


    }

    @Override
    protected void addListener() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPhone(String phone) {
        //刷新页面
       HttpManager.getInstance().doHttpDeal(accountSecurityApi);
    }

    HttpOnNextListener<BaseResultEntity> accountSecurityListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                AccountSecurityBean data = (AccountSecurityBean) baseResultEntity.getData();
                mobile = data.getMobile();
                String replace = null;
                if (mobile!=null) {
                    String substring = mobile.substring(3, 9);
                    replace = mobile.replace(substring, "******");
                    Log.e("wcx", "mobile: " + mobile + "substring:" + substring + "replace:" + replace);
                }
                String finalReplace = replace;
                String userName = data.getUserName();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (data.isIsBindingWx()) {
                            tv_bind_wx.setText("已绑定");
                        } else {
                            tv_bind_wx.setText("点击绑定");
                        }
                        if (mobile != null) {
                            tv_up_phone.setText(finalReplace);
                        } else {
                            tv_up_phone.setText("点击绑定");
                        }
                        tv_user_name.setText(userName);
                    }
                });
            }
        }
    };

    @OnClick({R.id.rl_up_pwd, R.id.rl_up_phone, R.id.rl_bind_wx})
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.rl_up_phone:
                String s = tv_up_phone.getText().toString();
                if (s.equals("点击绑定")) {
                    startActivity(BindPhoneActivity.queryIntent(AccountSecurityActivity.this));
                } else {
                    EventBus.getDefault().postSticky(mobile);
                    startActivity(UpPhoneActivity.queryIntent(AccountSecurityActivity.this));
                }
                break;
            case R.id.rl_up_pwd:
                Intent intent = UpPwdActivity.queryIntent(AccountSecurityActivity.this);
                intent.putExtra("mobile", mobile);
                startActivity(intent);
                break;
            case R.id.rl_bind_wx:
                String str = tv_bind_wx.getText().toString();
                if (str.equals("点击绑定")) {
                    wxBind();
                } else {
                    showDialog();
                }
                break;
        }
    }

    private void wxBind() {
        //切换用户就会去获取用户信息,每一次授权都会获取用户信息
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        mShareAPI.get(this).setShareConfig(config);

        mShareAPI.getPlatformInfo(AccountSecurityActivity.this, SHARE_MEDIA.WEIXIN, umAuthListener);

    }

    UMAuthListener umAuthListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            // ToastTools.showPublicToast("授权开始了");
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
           // ToastTools.showPublicToast("授权成功");


            String iconurl = data.get("iconurl");
            String uid = data.get("uid");
            String name = data.get("name");
            String sex = data.get("gender");
            String city = data.get("city");
            String openid = data.get("openid");
            String province = data.get("province");
            String languzge = data.get("languzge");
            String country = data.get("country");

            WeChatBean weChatBean = new WeChatBean(openid, name, 1, languzge, city, province, country, iconurl,new ArrayList<>(),uid);
            Gson gson = new Gson();
            String s = gson.toJson(weChatBean);


            Log.e("wcx", "iconurl: " + iconurl + "     uid: " + uid + "    " + "name: " + name);

            AccountWxBindApi accountWxBindApi = new AccountWxBindApi(AccountSecurityActivity.this, httpOnNextListener);
            accountWxBindApi.setShowProgress(true);
            accountWxBindApi.setCancel(false);
            accountWxBindApi.setArgument(s,SharedPreferencesUtil.getLoginToken());
            HttpManager.getInstance().doHttpDeal(accountWxBindApi);

        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
//            ToastTools.showPublicToast("失败");
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            // ToastTools.showPublicToast("取消了");
        }
    };

    HttpOnNextListener<BaseResultEntity> httpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                tv_bind_wx.setText("已绑定");
            }
            ToastTools.showPublicToast(baseResultEntity.getMsg());
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
        }
    };

    private void showDialog() {

       CustomDialog customDialog = new CustomDialog(this, R.layout.account_dialog);

        customDialog.show();
        customDialog.setCanceledOnTouchOutside(false);

        customDialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.cancel();
            }
        });
        customDialog.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unBindWx();
                customDialog.cancel();
            }
        });
    }

    private void unBindWx() {
        UnBindWxApi unBindWxApi = new UnBindWxApi(this,unBindWxListener );
        unBindWxApi.setToken(login_token);
        HttpManager.getInstance().doHttpDeal(unBindWxApi);
    }

    HttpOnNextListener<BaseResultEntity> unBindWxListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                tv_bind_wx.setText("点击绑定");
            }else {
                Toast toast = Toast.makeText(AccountSecurityActivity.this, baseResultEntity.getMsg() + "  " + baseResultEntity.getCode(), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER,0,0);
                toast.show();            }
        }
    };

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, AccountSecurityActivity.class);
        return intent;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bind != null) {
            bind.unbind();
        }
        EventBus.getDefault().unregister(this);
    }

}
